﻿/* *********************************************
 * Crypto libary : SHA module
 * Christiaan Rakowski 20110825
 * This module will compute the hash of the input string using a hash of the SHA family
 * ********************************************/

using System;
using System.Security.Cryptography;
using System.Text;

namespace CryptoCs
{
	namespace Hashing
	{
		public class SHA
		{
			public static string GetHash(SHAType type, String input, String salt)
			{
				switch (type)
				{
					case SHAType.SHA1:
						{
							SHA1CryptoServiceProvider sha1Hash = new SHA1CryptoServiceProvider();
							if (!String.IsNullOrEmpty(salt))
							{
								input = salt + input + salt;
							}
							byte[] data = sha1Hash.ComputeHash(Encoding.UTF8.GetBytes(input));							

							StringBuilder sBuilder = new StringBuilder();
							for (int i = 0; i < data.Length; i++)
							{
								sBuilder.Append(data[i].ToString("x2"));
							}
							return sBuilder.ToString();

							//return Encoding.UTF8.GetString(data);
						}
					case SHAType.SHA512:
						{
							SHA512 sha512Hash = new SHA512Managed();
							if (!String.IsNullOrEmpty(salt))
							{
								input = salt + input + salt;
							}
							byte[] data = sha512Hash.ComputeHash(Encoding.UTF8.GetBytes(input));

							StringBuilder sBuilder = new StringBuilder();
							for (int i = 0; i < data.Length; i++)
							{
								sBuilder.Append(data[i].ToString("x2"));
							}
							return sBuilder.ToString();

							//return Encoding.UTF8.GetString(data);
						}
					default:
						{
							return "";
						}
				}	
			}
			public static bool VerifyHash(SHAType type, String input, String salt, String hash)
			{
				String hashOfInput = GetHash(type, input, salt);
				StringComparer comparer = StringComparer.OrdinalIgnoreCase;
				return (0 == comparer.Compare(hashOfInput, hash));
			}

			public enum SHAType
			{
				SHA1,
				SHA512
			};
		}
	}
}
